package erp.education.web.interceptors;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class SessionInterceptor implements Interceptor {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		ActionContext context = actionInvocation.getInvocationContext();

		String tempActionResult = "";

		Map<String, Object> sessionMap = context.getSession();
		Map<String, Object> parameters = null;
		Map<String, String> skipUrl = new HashMap<String, String>();
		skipUrl.put("login", "login");
		skipUrl.put("", "");
		skipUrl.put("validateLogin", "validateLogin");
		HttpServletRequest request = (HttpServletRequest) context
				.get(ServletActionContext.HTTP_REQUEST);
		tempActionResult = actionInvocation.getInvocationContext().getName();

		if (null == sessionMap.keySet() || (null == sessionMap)
				|| (sessionMap.isEmpty())) {
			if (!(skipUrl.containsKey(tempActionResult))) {

				return "inValidSession";
			}
		} else {
			if (skipUrl.containsKey(tempActionResult)
					&& null == sessionMap.keySet()) {

				return "validSession";
			}
		}
		try {
			tempActionResult = actionInvocation.invoke();
			File cssFolder = new File(request.getSession().getServletContext()
					.getRealPath("/css"));
			String[] directories = cssFolder.list(new FilenameFilter() {
				@Override
				public boolean accept(File current, String name) {
					return new File(current, name).isDirectory();
				}
			});
			List<String> uiThemes = new ArrayList<String>();
			Collections.addAll(uiThemes, directories);
			request.getSession().getServletContext()
					.setAttribute("uiThemes", uiThemes);

		} catch (Exception e) {
			// e.printStackTrace();
			if (e.getMessage().contains("userdetails")) {
				return "inValidSession";
			}
			request.setAttribute("ERROR_MSG", e.getMessage());
			System.out.println(request.getAttribute("ERROR_MSG"));
			System.out.println("Exception Raised Modifie Code Here");

			return "error";
		}

		return tempActionResult;
	}

}
